package com.ugoodtech.mdcc.web.controller;

        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved
         * Unauthorized copying of this file, via any medium is strictly prohibited
         * Proprietary and confidential
         * Written by Stone Shaw, 15/11/19
         */


import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.AliServiceUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Api(description = "OSS上传文件")
@Controller
@RequestMapping("/oss")
public class OssController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OssController.class);

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Value("${oss.bucket.name}")
    private String ossBucketName;
    @Value("${oss.photo.bucket.name}")
    private String ossPhotoBucketName;


    @ApiOperation("上传文件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadFile(
            @ApiParam("文件数据") @RequestParam(value = "file") MultipartFile file
    ) throws Exception {
        String[] files = file.getOriginalFilename().split("\\.");
        String dir = "backend/" + System.currentTimeMillis() + "." + files[files.length - 1];
        AliServiceUtil.putObject(file.getInputStream(), dir, "finx");
        return JsonResponse.successResponseWithData(dir);
    }
    @ApiOperation("上传模板文件")
    @RequestMapping(value = "/uploadTemplateFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadTemplateFile( @ApiParam("文件数据") @RequestParam(value = "file") MultipartFile file
    ) throws Exception {
       String[] files = file.getOriginalFilename().split("\\.");
        String dir = "template/performance_plan" + System.currentTimeMillis() + "." + files[files.length - 1];
        AliServiceUtil.putObject(file.getInputStream(), dir, ossPhotoBucketName);
        return JsonResponse.successResponseWithData(dir);
    }


    @ApiOperation("获取图片")
    @RequestMapping(value = "/getFile", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getFile(@ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId, HttpServletRequest request) throws Exception {
//        isUserLogin();
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (null != stationReport) {
            SimpleDateFormat inFile = new SimpleDateFormat(Constants.SHORT_DATE_FORMAT);
            String templetPath = request.getSession().getServletContext().getRealPath("");
            String zipFileName = inFile.format(new Date()) + ".zip";
            String zipPath = templetPath + "/zipFile/" + zipFileName;
            File file = new File(zipPath);
            FileOutputStream fos = new FileOutputStream(file);
            ZipOutputStream zip = new ZipOutputStream(fos);
            if (stationReport.getCategory().equals(Constants.TECHCOLOR_REPORT)) {
                List<String> photoStr = getColorReportPhoto(reportId);
                for (String str : photoStr) {
                    String fileName = System.currentTimeMillis() + ".jpg";
                    String filePath = templetPath + "/colorImages/" + fileName;
                    AliServiceUtil.downLoad(str, ossBucketName, filePath);

                    ZipEntry entry = new ZipEntry(filePath);
                    zip.putNextEntry(entry);
                    InputStream in = new FileInputStream(filePath);
                    byte[] data = toByteArray(in);
                    in.close();
                    zip.write(data);
                }
            } else if (stationReport.getCategory().equals(Constants.SERVICE_REPORT)) {
                StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(reportId, 158L);
                if (null != regularServiceReport && StringUtils.isNotEmpty(regularServiceReport.getAnswerPhoto())) {
                    String fileName = +System.currentTimeMillis() + ".jpg";
                    String filePath = templetPath + "/serviceImages/" + fileName;
                    AliServiceUtil.downLoad(regularServiceReport.getAnswerPhoto(), ossBucketName, filePath);

                    ZipEntry entry = new ZipEntry(filePath);
                    zip.putNextEntry(entry);
                    InputStream in = new FileInputStream(filePath);
                    byte[] data = toByteArray(in);
                    in.close();
                    zip.write(data);
                }
            }
            zip.closeEntry();
            zip.close();
            String filePath = Constants.v_starServiceUrl + "/zipFile/" + zipFileName;
            return JsonResponse.successResponseWithData(filePath);
        }
        return JsonResponse.successResponseWithData("");
    }


    @ApiOperation("上传图片")
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadPhoto(
            @ApiParam("上传者ID") @RequestParam(value = "loginUserId") Long loginUserId,
            @ApiParam("图片文件数据") @RequestParam(value = "file") MultipartFile file,
            @ApiParam("报告类型") @RequestParam(value = "reportPath", required = false) String reportPath,
            @ApiParam("维修站ID") @RequestParam(value = "stationId", required = false) Long stationId,
            @ApiParam("问题ID") @RequestParam(value = "questionId", required = false) String questionId
    ) throws Exception {
        /**
         * **********************************************
         * 新加参数 用于划分每个维修站的照片
         */
        User clientUser = userRepository.findOne(loginUserId);
        logger.info("**********************************************");
        logger.info("<<<<<<<<<开始上传照片>>>>>>>>>>");
        logger.info("<<<<<<<<<上传照片用户ID为：" + clientUser.getId() + ">>>>>>>>>>");
        logger.info("<<<<<<<<<上传的维修站ID为：" + stationId + ">>>>>>>>>>");
        logger.info("<<<<<<<<<上传的问题ID为：" + questionId + ">>>>>>>>>>");
        if (stationId != null && stationId != 0) {
            Station station = stationRepository.findOne(stationId);
            if (station == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
            }
        }
        String path = "";
        if (StringUtils.isNotEmpty(reportPath)) {
            if (reportPath.equals(Constants.OSS_SERVICE)) {
                path = "backend/stations/" + stationId + "/" + Constants.OSS_SERVICE + "/";
            }
            if (reportPath.equals(Constants.OSS_COLOR)) {
                path = "backend/stations/" + Constants.OSS_COLOR + "/";
            }
            if (reportPath.equals(Constants.OSS_PAINT)) {
                path = "backend/stations/" + stationId + "/" + Constants.OSS_PAINT + "/";
            }
        }
        Long time = System.currentTimeMillis();
        String fileName = "";
        if (StringUtils.isNotEmpty(questionId)) {
            fileName = time + "_" + questionId + "_" + file.getOriginalFilename();
        } else {
            fileName = time + "_" + file.getOriginalFilename();
        }
        if (fileName.indexOf(".") == -1) {
            fileName += ".jpg";
            logger.info("原文件名没有后缀");
        }
        String realPath = path + fileName;
        /**
         * **********************************************
         */

        logger.info("原始文件名" + file.getOriginalFilename());
        String dir = "backend/photo/" + time + "_" + file.getOriginalFilename();
        if (dir.indexOf(".") == -1) {
            dir += ".jpg";
            logger.info("原文件名没有后缀");
        }
        logger.info("文件路径为" + dir);
        if (StringUtils.isNotEmpty(realPath)) {
            AliServiceUtil.putObject(file.getInputStream(), realPath, ossPhotoBucketName);
            logger.info(System.currentTimeMillis() - time + "");
            logger.info("文件路径为" + realPath);
            return JsonResponse.successResponseWithData(realPath);
        } else {
            AliServiceUtil.putObject(file.getInputStream(), dir, ossPhotoBucketName);
            logger.info(System.currentTimeMillis() - time + "");
            return JsonResponse.successResponseWithData(dir);
        }
    }


    private List<String> getColorReportPhoto(Long reportId) {
        List<String> photoStr = new ArrayList<>();
        StationColorReport stationColorReport = stationColorReportRepository.selectReport(reportId, 5L);
        if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerPhoto())) {
            photoStr.add(stationColorReport.getAnswerPhoto());
        }
        stationColorReport = stationColorReportRepository.selectReport(reportId, 6L);
        if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerPhoto())) {
            photoStr.add(stationColorReport.getAnswerPhoto());
        }
        stationColorReport = stationColorReportRepository.selectReport(reportId, 25L);
        if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerPhoto())) {
            photoStr.add(stationColorReport.getAnswerPhoto());
        }
        stationColorReport = stationColorReportRepository.selectReport(reportId, 50L);
        if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerPhoto())) {
            photoStr.add(stationColorReport.getAnswerPhoto());
        }
        stationColorReport = stationColorReportRepository.selectReport(reportId, 58L);
        if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerPhoto())) {
            photoStr.add(stationColorReport.getAnswerPhoto());
        }
        return photoStr;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


}
